package com.carkeeper.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carkeeper.dto.EmployeeDTO;
import com.carkeeper.exception.BussinessException;
import com.carkeeper.pojo.EmployeePO;
import com.carkeeper.service.EmployeeService;
import com.carkeeper.utils.JwtUtil;
import com.carkeeper.vo.EmployeeQueryParamVO;
import com.carkeeper.vo.LoginVO;
import com.carkeeper.vo.Pager;
import com.carkeeper.vo.ProfileVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @version : 1.0
 * @outhor : zwk
 * @data : Create in 2020-05-26
 * @description :
 */
@RestController
@RequestMapping("/user")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;


    @GetMapping
    public Pager<EmployeePO> findByPage(EmployeeQueryParamVO paramVo){
        Page<EmployeePO> employeePOPage = employeeService.findByPage(paramVo);
        employeePOPage.getRecords().forEach(po ->po.setPassword(null));
        return new Pager<>(
                employeePOPage.getTotal(),
                employeePOPage.getPages(),
                employeePOPage.getSize(),
                employeePOPage.getCurrent(),
                employeePOPage.getRecords());
    }


    /**
     * 新增
     * @param po
     * @return
     */
    @PostMapping
    public Boolean save(@RequestBody EmployeePO po){
        return employeeService.saveAndUpdate(po);
    }

    /**
     * 获取员工列表
     * @param queryDTO
     * @return
     */
    @PostMapping("/list")
    public List<EmployeeDTO> findAll(@RequestBody EmployeeDTO queryDTO){
        List<EmployeePO> list = employeeService.list(queryDTO);
        return list.stream().map(po->{
            EmployeeDTO dto = new EmployeeDTO();
            BeanUtils.copyProperties(po,dto);
            dto.setPassword(null);
            return dto;
        }).collect(Collectors.toList());
    }

    @PutMapping("/{id}")
    public Boolean update(@RequestBody EmployeePO employeePO){
        return employeeService.saveAndUpdate(employeePO);
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Long id) {
        return employeeService.delete(id);
    }

    /**
     * 修改用户
     *
     * @param id
     * @param password
     * @return
     */
    @PutMapping("/{id}/{password}")
    public boolean update(@PathVariable Long id, @PathVariable String password) {
        EmployeePO po = new EmployeePO();
        po.setId(id);
        po.setPassword(password);

        return employeeService.saveAndUpdate(po);
    }

    //id查员工
    @GetMapping("/{id}")
    public EmployeeDTO findById(@PathVariable(value = "id") Long id) {
        EmployeeDTO dto = new EmployeeDTO();
        EmployeePO po = employeeService.findById(id);
        if (po != null){
            BeanUtils.copyProperties(po,dto);
        }
        return dto;
    }


    /**
     * 登陆
     *
     * @param loginVO
     * @return
     */
    @PostMapping("/login")
    public LoginVO login(@RequestBody LoginVO loginVO) {
        if (StringUtils.isEmpty(loginVO.getUsername())) {
            throw new BussinessException("用户名不能为空");
        }
        if (StringUtils.isEmpty(loginVO.getPassword())) {
            throw new BussinessException("密码不能为空");

        }
        EmployeePO employeePO = employeeService.login(loginVO.getUsername(), loginVO.getPassword());

        //登录成功生成jwt
        String jwt = JwtUtil.createJWT(employeePO.getUsername(), null);

        //将jwt返回
        LoginVO vo = new LoginVO();
        vo.setToken(jwt);
        return vo;
    }

    /**
     * 登陆
     *
     * @return
     */
    @GetMapping("/profile")
    public ProfileVO profile(@RequestHeader("Authorization") String authorization) throws Exception {
        String token = authorization.replace("VEA-ADMIN ", "");
        Claims claims = JwtUtil.parseJWT(token);
        String subject = claims.getSubject();
        ObjectMapper om = new ObjectMapper();
        Map<String, Object> claimsMap = om.readValue(subject, Map.class);
        String username = String.valueOf(claimsMap.get("username"));
        EmployeePO po = employeeService.loadUserByUsername(username);
        ProfileVO vo = new ProfileVO();
        vo.setUsername(po.getUsername());
        vo.setId(po.getId());
        vo.setName(po.getName());
        return vo;
    }
}
